﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using FreedomERP.Models;
using FreedomERP.Comm;
using FreedomERP.Services.Bd;
using FreedomERP.Services.Bd.Impl;
using System.Collections;
using Ext.Net.MVC;
using FreedomERP.Comm.Utils;
using FreedomERP.Models.Bd;
using FreedomERP.Filter;

namespace FreedomERP.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        public IBdAccountService accountService { get; set; }
        public IBdRoleService roleService { get; set; }
        IBdCategoryService categoryService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (accountService == null) { accountService = new BdAccountServiceImpl(); }
            if (roleService == null) { roleService = new BdRoleServiceImpl(); }
            if (categoryService == null) { categoryService = new BdCategoryServiceImpl(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(string txtUsername, string txtPassword, string returnUrl)
        {
            BdAccount account = accountService.GetAccountByFAccount(txtUsername);
            if (account == null)
            {
                return new AjaxResult() { ErrorMessage = ConstNoteMessage.LOGIN_ACCOUNT_IS_NOT_EXIST };
            }
            else if (!account.FPassword.Equals(MD5Utils.MD5Encrypt(txtPassword)))
            {
                return new AjaxResult() { ErrorMessage = ConstNoteMessage.LOGIN_PASSWORD_ERROR };
            }
            else if (account.BdCategory == null || !account.BdCategory.FNumber.Equals(ConstData.ACCOUNT_STATUS_YES))
            {
                return new AjaxResult() { ErrorMessage = ConstNoteMessage.LOGIN_ACCOUNT_IS_LIMITED };
            }
            else
            {
                HttpContext.Session["user"] = account;
                return this.RedirectToAction("Index", "Home");
            }
        }

        /*
         * 帐号列表页面
         * 
         */
        [CheckSessionFilterAttribute]
        public ActionResult AccountIndex()
        {
            return View();
        }

        /*
         * 帐号分页列表
         */
        [CheckSessionFilterAttribute]
        public AjaxStoreResult AccountListPaging(int start, int limit, string dir, string sort, string accountParam, string roleParam, string statusParam)
        {
            int tatalCount = 0;

            string currAccountOrgunitFId = BaseController.GetCurrLoginAccountOrgunitFId();

            Hashtable filters = new Hashtable();
            filters.Add("accountParam", accountParam);
            filters.Add("roleParam", roleParam);
            filters.Add("statusParam", statusParam);
            filters.Add("orgunitParam", currAccountOrgunitFId);

            PagingParams pgp = new PagingParams(sort, OrderDirection.ToDirection(dir), start, limit, filters);

            List<BdAccount> accountListTemp = accountService.QueryAccountPaggingByParam(pgp, out tatalCount);

            List<BdAccountView> accountList = new List<BdAccountView>();
            foreach (BdAccount account in accountListTemp)
            {
                BdAccountView accountTemp = new BdAccountView();
                accountTemp.FId = account.FId;
                accountTemp.FAccount = account.FAccount;
                accountTemp.FPassword = account.FPassword;
                accountTemp.FRoleId = account.BdRole == null ? "" : account.BdRole.FName;
                accountTemp.FStatusId = account.BdCategory == null ? "" : account.BdCategory.FName;
                accountList.Add(accountTemp);
            }
            AjaxStoreResult accountPaging = new AjaxStoreResult(accountList, tatalCount);
            return accountPaging;
        }

        /*
        * 添加、修改帐号
        */
        [CheckSessionFilterAttribute]
        public AjaxFormResult SaveAccountEdit(string FId, FormCollection values)
        {
            AjaxFormResult response = new AjaxFormResult();
            string ResultMsg = string.Empty;
            bool ResultBool = true;

            string currAccountOrgunitFId = BaseController.GetCurrLoginAccountOrgunitFId();

            try
            {
                string FAccount = values["FAccount"];
                string FPassword = values["FPassword"];
                string FRePassword = values["FRePassword"];
                string FRoleId = values["FRoleId_value"];
                string FStatusId = values["FStatusId_value"];
                if (!FPassword.Equals(FRePassword))
                {
                    ResultBool = false;
                    ResultMsg = ConstNoteMessage.PASSWORD_INPUT_ERROR;
                }
                if (ResultBool)
                {
                    if (FId == null || FId.Equals(""))   //新增
                    {
                        BdAccount accountNew = new BdAccount();
                        accountNew.FId = GuidUtils.getGuid();
                        if (accountService.GetAccountByFAccount(FAccount) != null)
                        {
                            throw new Exception("该用户名已存在，无法添加。");
                        }
                        accountNew.FAccount = FAccount;
                        accountNew.FPassword = MD5Utils.MD5Encrypt(FPassword);
                        accountNew.FCreateTime = DateTime.Now;
                        accountNew.FRoleId = FRoleId;
                        accountNew.FStatusId = FStatusId;
                        accountNew.FOrgunitId = currAccountOrgunitFId;

                        accountService.AddAccount(accountNew);
                    }
                    else         //更新
                    {
                        BdAccount accountOld = new BdAccount();
                        accountOld.FId = FId;
                        accountOld.FAccount = FAccount;
                        accountOld.FPassword = FPassword;
                        accountOld.FRoleId = FRoleId;
                        accountOld.FStatusId = FStatusId;

                        accountService.ModifyAccount(accountOld);
                    }
                    ResultBool = true;
                    ResultMsg = ConstNoteMessage.SAVE_SUCCESS;
                }
            }
            catch (Exception e)
            {
                ResultBool = false;
                ResultMsg = e.Message;
            }

            response.Success = ResultBool;
            response.ExtraParams["msg"] = ResultMsg;
            return response;
        }

        /*
        * 根据FId获取帐号信息
        */
        [CheckSessionFilterAttribute]
        public AjaxStoreResult GetAccountMsgByFId(string FId)
        {
            List<BdAccountView> list = new List<BdAccountView>();
            BdAccount account = accountService.GetAccountByFId(FId);
            if (account != null)
            {
                BdAccountView accountTemp = new BdAccountView();
                accountTemp.FId = account.FId;
                accountTemp.FAccount = account.FAccount;
                accountTemp.FPassword = account.FPassword;
                accountTemp.FRePassword = account.FPassword;
                accountTemp.FRoleId = account.FRoleId;
                accountTemp.FStatusId = account.FStatusId;
                list.Add(accountTemp);
            }
            return new AjaxStoreResult(list, list.Count);
        }

        /*
       * 根据FId删除帐号信息
       */
        [CheckSessionFilterAttribute]
        public AjaxResult DeleteAccount(string FId)
        {
            AjaxResult response = new AjaxResult();
            try
            {
                accountService.DeleteAccount(FId);
            }
            catch (Exception e)
            {
                response.ErrorMessage = ConstNoteMessage.DELETE_FAILURE+":"+e.Message;
            }
            return response;
        }

        /// <summary>
        /// 获取角色列表
        /// 作者：梁建东
        /// </summary>
        [CheckSessionFilterAttribute]
        public AjaxStoreResult GetRoleList()
        {
            List<BdRole> roleList = roleService.QueryRoleListByFOrgunit(null);

            List<BdRoleView> listView = new List<BdRoleView>();

            if (roleList != null)
            {
                foreach (BdRole role in roleList)
                {
                    BdRoleView roleView = new BdRoleView();
                    roleView.FId = role.FId;
                    roleView.FName = role.FName;
                    listView.Add(roleView);
                }
            }

            return new AjaxStoreResult(listView, listView.Count);
        }

        /// <summary>
        /// 获取状态列表
        /// 作者：梁建东
        /// </summary>
        [CheckSessionFilterAttribute]
        public AjaxStoreResult GetOrderStatusList()
        {
            List<BdCategory> categoryList = categoryService.QueryCategoryListByFType(ConstData.CATEGORY_ACCOUNT_STATUS);

            List<BdCategoryView> listView = new List<BdCategoryView>();

            if (categoryList != null)
            {
                foreach (BdCategory category in categoryList)
                {
                    BdCategoryView categoryView = new BdCategoryView();
                    categoryView.FID = category.FId;
                    categoryView.FName = category.FName;
                    listView.Add(categoryView);
                }
            }

            return new AjaxStoreResult(listView, listView.Count);
        }

        /// <summary>
        /// 修改密码页面
        /// 作者：梁建东
        /// </summary>
        [CheckSessionFilterAttribute]
        public ActionResult AccountPassword()
        {
            return View();
        }

        /// <summary>
        /// 修改密码
        /// 作者：梁建东
        /// </summary>
        [CheckSessionFilterAttribute]
        public ActionResult ChangePassword(string txtOldPassword, string txtNewPassword, string txtRePassword)
        {
            BdAccount curAccount = BaseController.GetCurrLoginAccount();
            if (curAccount != null)
            {
                if (!curAccount.FPassword.Equals(MD5Utils.MD5Encrypt(txtOldPassword)))
                {
                    return new AjaxResult() { ErrorMessage = ConstNoteMessage.CHANGE_PASSWORD_OLD_ERROR };
                }
                else if (!txtNewPassword.Equals(txtRePassword))
                {
                    return new AjaxResult() { ErrorMessage = ConstNoteMessage.CHANGE_PASSWORD_RE_ERROR };
                }
                else
                {
                    try
                    {
                        accountService.ChangePassword(curAccount.FId, MD5Utils.MD5Encrypt(txtNewPassword));
                        curAccount.FPassword = MD5Utils.MD5Encrypt(txtNewPassword);
                        return new AjaxResult() { Result = "true" };
                    }
                    catch (Exception e)
                    {
                        return new AjaxResult() { ErrorMessage = ConstNoteMessage.SAVE_FAILURE };
                    }
                }
            }
            else
            {
                return new AjaxResult() { ErrorMessage = ConstNoteMessage.LOGIN_STATUS_UNUSE };
            }
        }

        /// <summary>
        /// 退出登录
        /// 作者：梁建东
        /// </summary>
        public ActionResult LogOut()
        {
            HttpContext.Session.Remove("user");
            return this.RedirectToAction("LogOn", "Account");
        }
    }
}
